import { exec } from 'child_process'
import { promisify } from 'util'
import os from 'os'
import Registry from 'winreg'

const execAsync = promisify(exec)

class SystemProxyManager {
  static async setSystemProxy(host, port) {
    const platform = os.platform()
    
    try {
      // if (platform === 'win32') {
      //   // Windows 设置系统代理
      //   await execAsync(
      //     `reg add "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v ProxyEnable /t REG_DWORD /d 1 /f & ` +
      //     `reg add "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v ProxyServer /t REG_SZ /d ${host}:${port} /f & ` +
      //     // 设置代理绕过列表，允许一些本地地址直接访问
      //     `reg add "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v ProxyOverride /t REG_SZ /d "localhost;127.0.0.1;*.local;*.localhost;<local>" /f`
      //   )
      //   // 设置 PAC 文件为空，确保使用代理而不是 PAC
      //   await execAsync(
      //     `reg add "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v AutoConfigURL /t REG_SZ /d "" /f`
      //   )
      //   // 设置不绕过本地地址
      //   await execAsync(
      //     `reg add "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v ProxyOverride /t REG_SZ /d "<local>" /f`
      //   )
      //   // 通知系统代理设置已更改
      //   await execAsync('netsh winhttp import proxy source=ie')
      // }

      if (os.platform() === 'win32') {
        const regKey = new Registry({
          hive: Registry.HKCU,
          key: '\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings'
        })
        
        await Promise.all([
          new Promise((resolve, reject) => {
            regKey.set('ProxyEnable', Registry.REG_DWORD, 1, (err) => {
              err ? reject(err) : resolve()
            })
          }),
          new Promise((resolve, reject) => {
            regKey.set('ProxyServer', Registry.REG_SZ, `${host}:${port}`, (err) => {
              err ? reject(err) : resolve()
            })
          })
        ])
      } else if (platform === 'darwin') {
        // macOS 设置系统代理
        const networkServices = await this.getMacNetworkServices()
        for (const service of networkServices) {
          await execAsync(`networksetup -setwebproxy "${service}" ${host} ${port}`)
          await execAsync(`networksetup -setsecurewebproxy "${service}" ${host} ${port}`)
          // 启用代理
          await execAsync(`networksetup -setwebproxystate "${service}" on`)
          await execAsync(`networksetup -setsecurewebproxystate "${service}" on`)
        }
      } else if (platform === 'linux') {
        // Linux (GNOME) 设置系统代理
        await execAsync(`gsettings set org.gnome.system.proxy mode 'manual'`)
        await execAsync(`gsettings set org.gnome.system.proxy.http host '${host}'`)
        await execAsync(`gsettings set org.gnome.system.proxy.http port ${port}`)
        await execAsync(`gsettings set org.gnome.system.proxy.https host '${host}'`)
        await execAsync(`gsettings set org.gnome.system.proxy.https port ${port}`)
      }
      return true
    } catch (error) {
      console.error('Set system proxy error:', error)
      return false
    }
  }

  static async removeSystemProxy() {
    const platform = os.platform()
    
    try {
      if (platform === 'win32') {
        // Windows 移除系统代理
        await execAsync(
          `reg add "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v ProxyEnable /t REG_DWORD /d 0 /f & ` +
          `reg add "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v ProxyServer /t REG_SZ /d "" /f`
        )
        // 清除 PAC 设置
        await execAsync(
          `reg add "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v AutoConfigURL /t REG_SZ /d "" /f`
        )
        // 通知系统代理设置已更改
        await execAsync('netsh winhttp import proxy source=ie')
      } else if (platform === 'darwin') {
        // macOS 移除系统代理
        const networkServices = await this.getMacNetworkServices()
        for (const service of networkServices) {
          await execAsync(`networksetup -setwebproxystate "${service}" off`)
          await execAsync(`networksetup -setsecurewebproxystate "${service}" off`)
        }
      } else if (platform === 'linux') {
        // Linux (GNOME) 移除系统代理
        await execAsync(`gsettings set org.gnome.system.proxy mode 'none'`)
      }
      return true
    } catch (error) {
      console.error('Remove system proxy error:', error)
      return false
    }
  }

  static async getMacNetworkServices() {
    try {
      const { stdout } = await execAsync('networksetup -listallnetworkservices')
      return stdout.split('\n')
        .filter(service => service && !service.includes('*'))
        .map(service => service.trim())
    } catch (error) {
      console.error('Get network services error:', error)
      return []
    }
  }

  static async getSystemProxyState() {
    const platform = os.platform()
    try {
      if (platform === 'win32') {
        const { stdout } = await execAsync(
          'reg query "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v ProxyEnable'
        )
        return stdout.includes('0x1')
      } else if (platform === 'darwin') {
        const networkServices = await this.getMacNetworkServices()
        if (networkServices.length > 0) {
          const { stdout } = await execAsync(
            `networksetup -getwebproxy "${networkServices[0]}"`
          )
          return stdout.toLowerCase().includes('enabled: yes')
        }
      } else if (platform === 'linux') {
        const { stdout } = await execAsync(
          'gsettings get org.gnome.system.proxy mode'
        )
        return stdout.trim() === "'manual'"
      }
      return false
    } catch (error) {
      console.error('Get proxy state error:', error)
      return false
    }
  }
}

export default SystemProxyManager